﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using TmU220PrintHelperV2d0.Singleton;
using ZhangLogSysV1d0;
using System.Web;

namespace TmU220PrintHelperV2d0.HttpHelper
{
    /// <summary>
    /// Http传输相关的函数
    /// </summary>
    public class HttpFunctionV2d0
    {
        
        /// <summary>
        /// 异步调用api接口，通过HttpClient
        /// </summary>
        /// <param name="interfaceUrl">接口url</param>
        /// <param name="messageBody">消息体字符串（对于get接口，保持空白）</param>
        /// <returns></returns>
        public static async Task<string> RunApiInterfaceByHttpClient(string interfaceUrl, string messageBody)
        {
            string resultString = string.Empty;
            if (string.IsNullOrEmpty(messageBody))
            {
                //get方法
                Task<string> resultTask = RunApiInterfaceGetByHttpClient(interfaceUrl);
                resultString = await resultTask;
            }
            else
            {
                //post方法
                Task<string> resultTask = RunApiInterfacePostByHttpclient(interfaceUrl, messageBody);
                resultString = await resultTask;
            }
            return resultString;
        }
        /// <summary>
        /// 运行Get类型的Api接口
        /// </summary>
        /// <param name="interfaceUrl">接口url</param>
        /// <returns>接口返回数据</returns>
        public static string RunApiInterfaceGet(string interfaceUrl)
        {
            string getReturnString = "";

                HttpWebRequest myRequest = null;
                HttpWebResponse myResponse = null;
            try
            {
                myRequest = (HttpWebRequest)WebRequest.Create(interfaceUrl);
                myRequest.Method = "GET";
                myRequest.Timeout = 1000;
                myResponse = (HttpWebResponse)myRequest.GetResponse();
                using (StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8))
                {
                    getReturnString = reader.ReadToEnd();
                }
            }
            catch (Exception ex)
            {
                SimpleLoger.Instance.Error(ex);
            }
            finally
            {
                if (myResponse != null)
                {
                    myResponse.Close();
                    myResponse = null;

                }
                if (myRequest != null)
                {
                    myRequest.Abort();
                    myRequest = null;
                }
            }
            return getReturnString;
        }
        /// <summary>
        /// 运行Get类型的Api接口 使用httpclient 异步
        /// </summary>
        /// <param name="interfaceUrl">接口url</param>
        /// <returns></returns>
        private static async Task<string> RunApiInterfaceGetByHttpClient(string interfaceUrl)
        {
            string rsponseString =string.Empty;
            try
            {
                using (HttpClient hClient = new HttpClient())
                {
                    HttpResponseMessage response = await hClient.GetAsync(interfaceUrl);
                    response.EnsureSuccessStatusCode();
                    rsponseString = await response.Content.ReadAsStringAsync();//.GetStringAsync(interfaceUrl); 
                }              
             
            }
            catch (Exception ex)
            {
                SimpleLoger.Instance.Error(ex);
            }
            return rsponseString;
        }
        /// <summary>
        /// 运行Post类型的Api接口
        /// </summary>
        /// <param name="interfaceUrl"></param>
        /// <param name="messageBody">消息体</param>
        /// <returns></returns>
        public static string RunApiInterfacePost(string interfaceUrl, string messageBody)
        {
            string postReturnString =string.Empty;
            //编码转换
            string urlMessageBody = System.Web.HttpUtility.UrlEncode(messageBody);// 
            //将消息体转为字节码
            byte[] bytesToPost = System.Text.Encoding.UTF8.GetBytes(messageBody); //转换为bytes数据
            HttpWebRequest myRequest = null;
                HttpWebResponse myResponse = null;
            try
            {
                myRequest = (HttpWebRequest)WebRequest.Create(interfaceUrl);
                myRequest.Method = "POST";
                myRequest.Timeout = 2000;
                myRequest.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
                myRequest.ContentLength = bytesToPost.Length;
                using (Stream reqStream = myRequest.GetRequestStream())
                {
                    //写入流
                    reqStream.Write(bytesToPost, 0, bytesToPost.Length);
                }
                myResponse = (HttpWebResponse)myRequest.GetResponse();
                if (myResponse != null)
                {
                    using (StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8))
                    {
                        postReturnString = reader.ReadToEnd();
                    }
                }
            }
            catch (Exception ex)
            {
                SimpleLoger.Instance.Error(ex.Message);
            }
            finally
            {
                if (myResponse != null)
                {
                    myResponse.Close();
                    myResponse = null;
                }
                if (myRequest != null)
                {
                    myRequest.Abort();
                    myRequest = null;
                }
            }
            return postReturnString;
        }
        /// <summary>
        /// UrlEncode编码
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string UrlEncode(string str)
        {
            StringBuilder sb = new StringBuilder();
            byte[] byStr = System.Text.Encoding.UTF8.GetBytes(str); //默认是System.Text.Encoding.Default.GetBytes(str)
            for (int i = 0; i < byStr.Length; i++)
            {
                sb.Append(@"%" + Convert.ToString(byStr[i], 16));
            }

            return (sb.ToString());
        }
        /// <summary>
        /// 运行Post类型的Api接口 使用httpclient 异步
        /// </summary>
        /// <param name="interfaceUrl">接口url</param>
        /// <param name="messageBody">消息体【name1=value1&name2=value2】</param>
        /// <returns></returns>
        public static async Task<string> RunApiInterfacePostByHttpclient(string interfaceUrl, string messageBody)
        {
            string rsponseString = string.Empty;           
            try
            {
                HttpContent httpContent = new StringContent(messageBody);
                //浏览器用x-www-form-urlencoded的编码方式把form数据转换成一个字串 【name1=value1&name2=value2】
                httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
                httpContent.Headers.ContentType.CharSet = "utf-8";
                using (HttpClient hClient = new HttpClient())
                {
                    HttpResponseMessage response = await hClient.PostAsync(interfaceUrl, httpContent);
                    response.EnsureSuccessStatusCode();
                    rsponseString = await response.Content.ReadAsStringAsync();//.GetStringAsync(interfaceUrl); 
                }
            }
            catch (Exception ex)
            {
                SimpleLoger.Instance.Error(ex);
            }
            return rsponseString;
        }
    } 
}
